package com.cjj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjj.common.convention.exception.ClientException;
import com.cjj.dao.entity.ForumPost;
import com.cjj.dao.entity.PostLike;
import com.cjj.dao.mapper.ForumPostMapper;
import com.cjj.dao.mapper.PostLikeMapper;
import com.cjj.service.PostLikeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PostLikeServiceImpl extends ServiceImpl<PostLikeMapper, PostLike> implements PostLikeService {

    private final PostLikeMapper postLikeMapper;
    private final ForumPostMapper forumPostMapper;

    /**
     * 用户点赞帖子
     */
    @Transactional(rollbackFor = Exception.class)
    public void likePost(Long postId, Long userId) {
        // 检查是否已经点赞
        if (hasLiked(postId, userId)) {
            throw new ClientException("已经点赞过该帖子");
        }

        // 添加点赞记录
        PostLike postLike = new PostLike()
                .setPostId(postId)
                .setUserId(userId);
        postLikeMapper.insert(postLike);

        // 更新帖子点赞数
        updatePostLikeCount(postId, 1);
    }

    /**
     * 用户取消点赞
     */
    @Transactional(rollbackFor = Exception.class)
    public void unlikePost(Long postId, Long userId) {
        // 删除点赞记录
        LambdaQueryWrapper<PostLike> wrapper = Wrappers.lambdaQuery(PostLike.class)
                .eq(PostLike::getPostId, postId)
                .eq(PostLike::getUserId, userId);

        int deleteCount = postLikeMapper.delete(wrapper);
        if (deleteCount > 0) {
            // 更新帖子点赞数
            updatePostLikeCount(postId, -1);
        }
    }

    /**
     * 检查用户是否点赞过帖子
     */
    public boolean hasLiked(Long postId, Long userId) {
        LambdaQueryWrapper<PostLike> wrapper = Wrappers.lambdaQuery(PostLike.class)
                .eq(PostLike::getPostId, postId)
                .eq(PostLike::getUserId, userId);
        return postLikeMapper.selectCount(wrapper) > 0;
    }

    /**
     * 批量检查用户点赞状态
     */
    public Map<Long, Boolean> batchCheckLikeStatus(List<Long> postIds, Long userId) {
        if (postIds == null || postIds.isEmpty() || userId == null) {
            return new HashMap<>();
        }

        LambdaQueryWrapper<PostLike> wrapper = Wrappers.lambdaQuery(PostLike.class)
                .in(PostLike::getPostId, postIds)
                .eq(PostLike::getUserId, userId)
                .select(PostLike::getPostId);

        List<PostLike> likes = postLikeMapper.selectList(wrapper);
        Set<Long> likedPostIds = likes.stream()
                .map(PostLike::getPostId)
                .collect(Collectors.toSet());

        // 构建结果Map
        Map<Long, Boolean> result = new HashMap<>();
        for (Long postId : postIds) {
            result.put(postId, likedPostIds.contains(postId));
        }

        return result;
    }

    /**
     * 更新帖子点赞数
     */
    private void updatePostLikeCount(Long postId, int delta) {
        LambdaUpdateWrapper<ForumPost> updateWrapper = Wrappers.lambdaUpdate(ForumPost.class)
                .eq(ForumPost::getPostId, postId)
                .setSql("like_count = like_count + " + delta);
        forumPostMapper.update(null, updateWrapper);
    }
}
